package com.atguigu.aspect;

import com.atguigu.annotations.CustomerLogAnnotation;
import com.atguigu.resp.ResultData;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

/**
 * 新建一个切面类 三个注解是标配
 * 新建一个切入点 pointcut往哪切
 * 五大通知随织入 业务落地切面成
 */

@Aspect
@Component
public class CustomerLogAspect {

    @Around("@annotation(com.atguigu.annotations.CustomerLogAnnotation)")
    public ResultData<String> logAspect(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        //获取方法签名
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();

        //获取方法
        Method method = methodSignature.getMethod();

        //获取方法中携带的注解
        CustomerLogAnnotation annotation = method.getAnnotation(CustomerLogAnnotation.class);
        if (annotation != null && annotation.enable()) {
            //添加日志
            System.out.println("方法开始前：添加日志");

            //获取开始时间戳
            long start = System.currentTimeMillis();
            ResultData<String> proceed = (ResultData<String>) proceedingJoinPoint.proceed();
            //获取结束时间戳
            long end = System.currentTimeMillis();

            //添加日志
            System.out.println("方法结束后：添加日志");

            //执行时间
            System.out.println("执行时间：" + (end - start) + "ms");
            return proceed;
        } else {
            return (ResultData<String>) proceedingJoinPoint.proceed();
        }
    }
}
